package com.ruoyi.novel.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.novel.domain.Chapters;
import com.ruoyi.novel.service.IChaptersService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.file.DocumentUtils;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUtils;
import java.io.File;

/**
 * 小说章节Controller
 * 
 * @author sjy
 * @date 2025-06-19
 */
@RestController
@RequestMapping("/novel/chapters")
public class ChaptersController extends BaseController
{
    @Autowired
    private IChaptersService chaptersService;

    /**
     * 查询小说章节列表
     */
    @PreAuthorize("@ss.hasPermi('novel:chapters:list')")
    @GetMapping("/list")
    public TableDataInfo list(Chapters chapters)
    {
        startPage();
        List<Chapters> list = chaptersService.selectChaptersList(chapters);
        return getDataTable(list);
    }

    /**
     * 导出小说章节列表
     */
    @PreAuthorize("@ss.hasPermi('novel:chapters:export')")
    @Log(title = "小说章节", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Chapters chapters)
    {
        List<Chapters> list = chaptersService.selectChaptersList(chapters);
        ExcelUtil<Chapters> util = new ExcelUtil<Chapters>(Chapters.class);
        util.exportExcel(response, list, "小说章节数据");
    }

    /**
     * 获取小说章节详细信息
     */
    @PreAuthorize("@ss.hasPermi('novel:chapters:query')")
    @GetMapping(value = "/{chapterId}")
    public AjaxResult getInfo(@PathVariable("chapterId") Long chapterId)
    {
        return success(chaptersService.selectChaptersByChapterId(chapterId));
    }



    /**
     * 新增小说章节
     */
    @PreAuthorize("@ss.hasPermi('novel:chapters:add')")
    @Log(title = "小说章节", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Chapters chapters)
    {
        return toAjax(chaptersService.insertChapters(chapters));
    }

    /**
     * 修改小说章节
     */
    @PreAuthorize("@ss.hasPermi('novel:chapters:edit')")
    @Log(title = "小说章节", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Chapters chapters)
    {
        return toAjax(chaptersService.updateChapters(chapters));
    }

    /**
     * 删除小说章节
     */
    @PreAuthorize("@ss.hasPermi('novel:chapters:remove')")
    @Log(title = "小说章节", businessType = BusinessType.DELETE)
	@DeleteMapping("/{chapterIds}")
    public AjaxResult remove(@PathVariable Long[] chapterIds)
    {
        return toAjax(chaptersService.deleteChaptersByChapterIds(chapterIds));
    }

    /**
     * 从Word文档导入章节内容
     * 根据章节ID获取章节信息，如果content是Word文件路径，则读取Word内容并更新到数据库
     * 
     * @param chapterId 章节ID
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('novel:chapters:edit')")
    @Log(title = "导入Word章节内容", businessType = BusinessType.UPDATE)
    @PostMapping("/importWordContent/{chapterId}")
    public AjaxResult importWordContent(@PathVariable Long chapterId)
    {
        try
        {
            // 1. 根据章节ID获取章节信息
            Chapters chapter = chaptersService.selectChaptersByChapterId(chapterId);
            if (chapter == null)
            {
                return error("章节不存在");
            }

            // 2. 获取content路径
            String contentPath = chapter.getContent();
            if (contentPath == null || contentPath.isEmpty())
            {
                return error("章节内容路径为空");
            }

            // 3. 判断是否为Word格式
            if (!DocumentUtils.isWordDocument(contentPath))
            {
                return error("章节内容不是Word文档格式");
            }

            // 4. 将相对路径转换为绝对路径
            String absolutePath = getAbsolutePath(contentPath);
            logger.info("章节内容路径: {} -> 绝对路径: {}", contentPath, absolutePath);

            // 5. 读取Word文档内容
            String wordContent = DocumentUtils.readWordContent(absolutePath);
            if (wordContent == null || wordContent.isEmpty())
            {
                return error("Word文档内容为空");
            }

            // 6. 更新章节内容
            chapter.setContent(wordContent);
            // 更新字数统计
            chapter.setWordCount((long) wordContent.length());

            // 7. 保存到数据库
            int result = chaptersService.updateChapters(chapter);
            
            return toAjax(result);
        }
        catch (Exception e)
        {
            logger.error("导入Word章节内容失败", e);
            return error("导入失败: " + e.getMessage());
        }
    }

    /**
     * 将相对路径转换为绝对路径
     * 
     * @param path 文件路径
     * @return 绝对路径
     */
    private String getAbsolutePath(String path)
    {
        // 检查是否已经是绝对路径（Windows: 包含盘符，Linux: 不以/profile开头的/路径）
        File file = new File(path);
        if (file.isAbsolute() && !path.startsWith("/profile") && !path.startsWith("\\profile"))
        {
            return path;
        }
        
        // 处理相对路径，移除 /profile 前缀（如果存在）
        String relativePath = path;
        if (path.startsWith("/profile/") || path.startsWith("/profile\\"))
        {
            relativePath = path.substring("/profile".length());
        }
        else if (path.startsWith("\\profile\\") || path.startsWith("\\profile/"))
        {
            relativePath = path.substring("\\profile".length());
        }
        
        // 标准化路径分隔符
        relativePath = relativePath.replace("/", File.separator).replace("\\", File.separator);
        
        // 拼接基础路径
        String basePath = RuoYiConfig.getProfile();
        if (basePath.endsWith(File.separator))
        {
            return basePath + relativePath.substring(relativePath.startsWith(File.separator) ? 1 : 0);
        }
        else
        {
            return basePath + (relativePath.startsWith(File.separator) ? relativePath : File.separator + relativePath);
        }
    }
}
